package com.ruoyi.trans.utils;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 导出至csv文件
 */
public class CsvUtil {

    /**
     * 写入csv文件
     *
     * @param headers  列头
     * @param data     数据内容
     * @param filePath 创建的csv文件路径
     */
    public static void writeCsv(String[] headers, List<Map<String, Object>> data, String filePath) {
        try {
            File file = new File(filePath);
            // 检查文件是否存在，如果不存在则创建
            if (!file.exists()) {
                File parent = file.getParentFile();
                if (parent != null &&!parent.exists()) {
                    parent.mkdirs();
                }
                file.createNewFile();
            }
            try (CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"))) {
                writer.writeNext(headers);
                for (Map<String, Object> lineData : data) {
                    String[] strData = new String[headers.length];
                    for (int i = 0; i < headers.length; i++) {
                        Object value = lineData.get(headers[i]);
                        strData[i] = value != null ? value.toString() : "";
                    }
                    writer.writeNext(strData);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出至多个csv文件
     */
    public void writeMuti() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch doneSignal = new CountDownLatch(2);

        List<Map<String, String>> recordList = new ArrayList<>();

        executorService.submit(new CsvExportThread("/Users/apple/ruoyi/uploadPath/0.csv", recordList, doneSignal));
        executorService.submit(new CsvExportThread("/Users/apple/ruoyi/uploadPath/1.csv", recordList, doneSignal));

        doneSignal.await();
        System.out.println("Finish!!!");
    }

    /**
     * @param colNames 表头部数据
     * @param mapKeys  查找的对应数据
     * @param dataList 集合数据
     */
    public static ByteArrayOutputStream doExport(String[] colNames, String[] mapKeys, List<Map<String, Object>> dataList) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
             CSVWriter writer = new CSVWriter(new OutputStreamWriter(os, "UTF-8"))) {
            writer.writeNext(colNames);
            for (Map<String, Object> map : dataList) {
                String[] row = new String[mapKeys.length];
                for (int i = 0; i < mapKeys.length; i++) {
                    Object value = map.get(mapKeys[i]);
                    row[i] = value != null ? value.toString() : "";
                }
                writer.writeNext(row);
            }
            writer.flush();
            return os;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HttpHeaders setCsvHeader(String fileName) {
        HttpHeaders headers = new HttpHeaders();
        try {
            // 设置文件后缀
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String filename = new String(fileName.getBytes("gbk"), "iso8859-1") + sdf.format(new Date()) + ".csv";
            headers.add("Pragma", "public");
            headers.add("Cache-Control", "max-age=30");
            headers.add("Content-Disposition", "attachment;filename=" + filename);
            headers.setContentType(MediaType.valueOf("application/vnd.ms-excel;charset=UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return headers;
    }
}

class CsvExportThread implements Runnable {
    private final String filePath;
    private final List<Map<String, String>> recordList;
    private final CountDownLatch doneSignal;

    public CsvExportThread(String filePath, List<Map<String, String>> recordList, CountDownLatch doneSignal) {
        this.filePath = filePath;
        this.recordList = recordList;
        this.doneSignal = doneSignal;
    }

    @Override
    public void run() {
        try {
            // 实现具体的导出逻辑
            String[] headers = {"header1", "header2"}; // 假设列头
            List<Map<String, Object>> data = new ArrayList<>();
            for (Map<String, String> record : recordList) {
                Map<String, Object> map = new HashMap<>();
                map.put("header1", record.get("key1"));
                map.put("header2", record.get("key2"));
                data.add(map);
            }
            CsvUtil.writeCsv(headers, data, filePath);
        } finally {
            doneSignal.countDown();
        }
    }
}